<template>
  <el-container class="login-container">
    <div class="form_container">
      <div>
        <div class="login-title">
          {{ formTitle }}
        </div>
        <div class="login" v-show="linkCurrentValue === 'login'">
          <el-form
              :model="loginForm"
              :rules="loginRules"
              ref="loginFormRef"
              label-width="100px"
              class="form"
          >
            <el-form-item prop="account">
              <el-input v-model="loginForm.account" placeholder="请输入学号或邮箱" clearable>
                <template #prefix>
                  <el-icon>
                    <User/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  type="password"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  show-password
              >
                <template #prefix>
                  <el-icon>
                    <Lock/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="verifyCode">
              <div class="registerContainer">
                <div class="registerContainer">
                  <el-input v-model="loginForm.verifyCode" placeholder="请输入验证码" clearable
                            @keyup.enter="handleLogin">
                    <template #prefix>
                      <el-icon>
                        <Key/>
                      </el-icon>
                    </template>
                  </el-input>
                  <img
                      class="registerImg"
                      :src="captchaSrc"
                      @click="getImg"
                      alt="#"/>
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                  :loading="fullscreenLoading"
                  type="primary" @click="handleLogin" class="login-btn">登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 注册 tab -->
        <div class="register" v-show="linkCurrentValue === 'register'">
          <el-form
              :model="registerForm"
              :rules="registerRules"
              ref="registerFormRef"
              label-width="100px"
              class="form"
          >
            <el-form-item prop="sno">
              <el-input v-model="registerForm.sno" placeholder="请输入学号" clearable>
                <template #prefix>
                  <el-icon>
                    <UserFilled/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" clearable>
                <template #prefix>
                  <el-icon>
                    <ChatDotRound/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="请输入用户名" clearable>
                <template #prefix>
                  <el-icon>
                    <User/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  type="password"
                  v-model="registerForm.password"
                  placeholder="请输入密码"
                  show-password
              >
                <template #prefix>
                  <el-icon>
                    <Lock/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                  type="password"
                  v-model="registerForm.confirmPassword"
                  placeholder="请再次输入密码"
                  show-password
              >
                <template #prefix>
                  <el-icon>
                    <Lock/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <!-- 修改后的验证码表单项 -->
            <el-form-item prop="verifyCode">
              <div class="registerContainer">
                <el-input
                    v-model="registerForm.verifyCode"
                    placeholder="请输入邮箱验证码"
                    clearable
                    @keyup.enter="handleRegister">
                  <template #prefix>
                    <el-icon>
                      <Key/>
                    </el-icon>
                  </template>
                </el-input>
                <el-button size="large" :disabled="isCounting" :loading="smsLoading" @click="sendEmailCode" type="primary">
                  {{ label }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                  :loading="fullscreenLoading"
                  type="primary" @click="handleRegister" class="login-btn">注册
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 跳转链接 -->
        <div class="jump-container" v-show="linkCurrentValue === 'register'">
          已有账号，去<span class="active" @click="linkClick('login')">登录</span>
        </div>
        <div class="jump-container" v-show="linkCurrentValue === 'login'">
          未注册，去<span class="active" @click="linkClick('register')">注册</span>
        </div>
      </div>
    </div>
  </el-container>
</template>


<script setup>
import {onMounted, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {User, Lock, Key, UserFilled, ChatDotRound} from '@element-plus/icons-vue'

import {useStateStore} from '@/stores/login.js'
import {useRoute, useRouter} from "vue-router";
import {login, logout, getInfo, getCodeImg, register} from "../api/login/login.js"
import useSmsCode from "@/utils/useSmsCode.js"

import useUserStore from "../stores/useUserStore.js"
import {REGEXP_SNO} from "@/utils/regex.js"

const fullscreenLoading = ref(false)
const userStore = useUserStore();
const stateValueStore = useStateStore()
const router = useRouter()
const route = useRoute()

const captchaSrc = ref("") // 避免缓存

let {label, isCounting, loading: smsLoading, getSmsCode} = useSmsCode();
// 表单引用
const loginFormRef = ref(null)
const registerFormRef = ref(null)
const linkCurrentValue = ref("login")
const formTitle = ref("账号登录")

// 页面挂载时根据当前路由设置状态
onMounted(() => {
  if (route.path === '/register') {
    linkCurrentValue.value = 'register'
    formTitle.value = '账号注册'
    stateValueStore.changeState("register")
  } else if (route.path === '/login') {
    // 默认登录页面
    linkCurrentValue.value = 'login'
    formTitle.value = '账号登录'
    stateValueStore.changeState("login")
  }
  getImg()
})

// 监听路由变化，保持内部状态同步
watch(() => route.path, (newPath) => {
  if (newPath === '/register') {
    linkCurrentValue.value = 'register'
    formTitle.value = '账号注册'
    stateValueStore.changeState("register")
  } else if (newPath === '/login') {
    linkCurrentValue.value = 'login'
    formTitle.value = '账号登录'
    stateValueStore.changeState("login")
  }
  getImg()
})

const getImg = async () => {
  const res = await getCodeImg()
  // 释放旧的 Blob URL，避免内存泄漏
  if (captchaSrc.value) {
    URL.revokeObjectURL(captchaSrc.value);
  }
  captchaSrc.value = URL.createObjectURL(res);
}

// 点击link进行路由跳转
const linkClick = (value) => {
  if (value === "login") {
    router.push({path: '/login'})
  } else if (value === "register") {
    router.push({path: '/register'})
  }
}

// 登录表单数据
const loginForm = ref({
  account: '',
  password: '',
  verifyCode: ''
})

// 注册表单数据
const registerForm = ref({
  sno: '',
  email: '',  // 确保email字段存在
  password: '',
  confirmPassword: '',
  verifyCode: '',
  username: ''
})


// 发送邮箱验证码方法
const sendEmailCode = async () => {
  if (!registerForm.value.email) {
    ElMessage.warning('请输入邮箱地址')
    return
  }
  await getSmsCode(registerForm.value.email)
}

// 修改注册表单验证规则
const registerRules = {
  sno: [
    {
      validator: (rule, value, callback) => {
        if (!value && !registerForm.value.email) {
          callback(new Error('学号和邮箱至少填写一项'))
        } else if (value && !REGEXP_SNO.test(value)) {
          callback(new Error('请输入11位学号'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']  // 增加 change 触发时机
    }
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (!value && !registerForm.value.sno) {
          callback(new Error('学号和邮箱至少填写一项'))
        } else if (value && !/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(value)) {
          callback(new Error('邮箱格式不正确'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']  // 增加 change 触发时机
    }
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  verifyCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'}
  ],
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请输入确认密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 登录提交处理
const handleLogin = () => {
  loginFormRef.value.validate(async valid => {
    if (valid) {
      fullscreenLoading.value = true
      try {
        const res = await userStore.login(loginForm.value)
        await userStore.getInfo()
        fullscreenLoading.value = false
        if (res.data.code === 200) {
          ElMessage.success('登录成功')
          router.push("/home")
        } else {
          ElMessage.error('登录失败')
          getImg()
        }
      } catch (e) {
        fullscreenLoading.value = false
        getImg()
      }

    }
  })
}

// 注册提交处理
const handleRegister = () => {
  registerFormRef.value.validate(async valid => {
    if (valid) {
      fullscreenLoading.value = true
      try {
        const res = await register(registerForm.value)
        fullscreenLoading.value = false
        if (res.data.code === 200) {
          ElMessage.success('注册成功, 为您跳转到登陆页进行登录')
          await router.push("/login")
        } else {
          ElMessage.error('注册失败')
          await getImg()
        }
      } catch (e) {
        fullscreenLoading.value = false
        await getImg()
      }
    } else {
      ElMessage.error('请检查输入')
      return false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-title {
  font-size: 26px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
}

.active {
  color: #409EFF;
  margin-left: 5px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s;
}

.active:hover {
  text-decoration: underline;
}

.form_container {
  padding: 40px;
  width: 450px;
  border-radius: 10px;
  background: white;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  margin: 0 auto;
}

.registerContainer .el-input {
  width: 260px;
}

.registerContainer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
}

.registerImg {
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.registerImg:hover {
  opacity: 0.8;
}

.jump-container {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

.login-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 4px;
}

:deep(.el-input__wrapper) {
  height: 45px;
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

:deep(.el-form-item__label) {
  font-size: 16px;
  width: 150px !important;
}

:deep(.el-form-item__error) {
  font-size: 14px;
}

:deep(.el-form-item) {
  width: 100%;
  margin-bottom: 25px;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.send-btn {
  width: 120px;
  margin-left: 10px;
  height: 40px;
}

.registerContainer .el-input {
  width: calc(100% - 130px); /* 调整输入框宽度适应按钮 */
}
</style>
